package com.achun.ximalayamvvm

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.widget.SeekBar
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.achun.ximalayamvvm.bean.TracksIndex
import com.achun.ximalayamvvm.databinding.ActivityPlayerBinding
import com.achun.ximalayamvvm.utils.ToastUtil
import com.achun.ximalayamvvm.view.custom.HimaPopupWindow
import com.achun.ximalayamvvm.vm.PlayerViewModel
import com.bumptech.glide.Glide
import com.ximalaya.ting.android.opensdk.model.track.Track
import java.text.SimpleDateFormat

class PlayerActivity : AppCompatActivity() {
    private lateinit var contentView: ActivityPlayerBinding
    private lateinit var currentTracks: List<Track>
    private var simpletime = SimpleDateFormat("mm:ss")
    private var isTouch = false
    private var playmode = HashMap<PlayMode, PlayMode>()
    private var currentMode = PlayMode.SORT
    private lateinit var rotateAnimation: ObjectAnimator
    private lateinit var himaPopupWindow: HimaPopupWindow
    private lateinit var enterAnimator: ValueAnimator
    private lateinit var exitAnimator: ValueAnimator

    enum class PlayMode {
        RANDOM, SORT, LOOP
    }

    companion object {
        const val POPWINDOW_DURATION = 700L
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        contentView =
            DataBindingUtil.setContentView<ActivityPlayerBinding>(this, R.layout.activity_player)
        initView()
        initViewModel(contentView)

    }

    private fun initView() {
        //跑马灯需要点击
        contentView.playerTitleTv.isSelected=true
        //属性动画
        rotateAnimation =
            ObjectAnimator.ofFloat(contentView.imageView,"rotation",0.0f,360.0f)
        rotateAnimation.run {
            duration = 10*1000
            interpolator=LinearInterpolator()
            repeatCount=ObjectAnimator.INFINITE
            repeatMode=ValueAnimator.RESTART
        }

        playmode[PlayMode.RANDOM] = PlayMode.SORT
        playmode[PlayMode.SORT] = PlayMode.LOOP
        playmode[PlayMode.LOOP] = PlayMode.RANDOM

        //初始化popupWindow
        himaPopupWindow = HimaPopupWindow()


        //设置属性动画
        //popwindow进入
        enterAnimator = ValueAnimator.ofFloat(1.0f, 0.7f)
        enterAnimator.duration = POPWINDOW_DURATION
        enterAnimator.addUpdateListener {
            var translateValue = it.animatedValue as Float
            com.achun.ximalayamvvm.utils.LogUtil.e(this, "透明度变化--$translateValue")
            //更新背景透明度
            updateBgAlpha(translateValue)

        }
        //popwindow关闭
        exitAnimator = ValueAnimator.ofFloat(0.7f, 1.0f)
        exitAnimator.duration = POPWINDOW_DURATION
        exitAnimator.addUpdateListener {
            var translateValue = it.animatedValue as Float
            updateBgAlpha(translateValue)
        }


    }

    //更新背景透明度
    fun updateBgAlpha(alpha: Float) {
        var window = window
        var attributes = window.attributes
        attributes.alpha = alpha
        window.attributes = attributes
    }

    private fun initViewModel(contentView: ActivityPlayerBinding?) {
        var playerViewModel = PlayerViewModel.instace
        //初始化映射模式
        playModeinit(playerViewModel, contentView!!)
        //监听播放列表及当前索引
        playerViewModel.getTracks().run {
            observe(this@PlayerActivity, Observer {
                himaPopupWindow.setDatas(it.tracks)
                himaPopupWindow.setPlayingIndex(it.position)

            })
            //监听当前播放歌曲
            playerViewModel.getTrack().run {
                observe(this@PlayerActivity) {
                    //更新当前页面
                    com.achun.ximalayamvvm.utils.LogUtil.e(this, "更新页面")
                    contentView?.run {
                        playerTitleTv.text = it.trackTitle
                        Glide.with(contentView.root).load(it.coverUrlMiddle).into(imageView)
                        var alltime = simpletime.format(it.duration * 1000)
                        playerAlltimeTv.text = alltime

                    }
                }
            }
            //监听进度条及播放时长
            playerViewModel.getProgressInfo().run {
                observe(this@PlayerActivity) {
                    contentView?.run {
                        playerCurrentTv?.text = simpletime.format(it.currentPos)
                        if (!isTouch)
                            playerDurationSb.progress = it.currentPos * 100 / it.duration
                    }
                }
            }
            //监听播放状态
            playerViewModel.getPlayStatus().run {
                observe(this@PlayerActivity) {
                    if (it) {
                        contentView!!.playerPlayorpauseIv.setImageResource(R.drawable.selecter_pause_btn)
                        if (!rotateAnimation.isStarted)
                        rotateAnimation.start()
                        else
                            rotateAnimation.resume()

                    } else {
                        contentView!!.playerPlayorpauseIv.setImageResource(R.drawable.selecter_play_btn)
                       if (rotateAnimation.isRunning){
                           rotateAnimation.pause()
                       }
                    }
                }
            }
            //初始化事件
            initEvent(playerViewModel)

        }

    }

    private fun playModeinit(playerViewModel: PlayerViewModel, contentView: ActivityPlayerBinding) {
        when (playerViewModel.getPlayMode()) {
            PlayMode.LOOP -> {
                contentView.playerModechangeIv.setImageResource(R.drawable.selecter_loop_one_btn)
            }
            PlayMode.RANDOM -> {
                contentView.playerModechangeIv.setImageResource(R.drawable.selecter_random_loop_btn)
            }
            PlayMode.SORT -> {
                contentView.playerModechangeIv.setImageResource(R.drawable.selecter_sort_loop_btn)
            }
        }
    }

    private fun initEvent(playerViewModel: PlayerViewModel) {
        contentView?.run {
            //播放暂停点击
            playerPlayorpauseIv?.setOnClickListener() {
                var isPlay = playerViewModel.playorPause()
                com.achun.ximalayamvvm.utils.LogUtil.e(this, "音乐是否播放--$isPlay")
                if (isPlay)
                    playerPlayorpauseIv.setImageResource(R.drawable.selecter_pause_btn)
                else
                    playerPlayorpauseIv.setImageResource(R.drawable.selecter_play_btn)
            }
            //播放下一首
            playerNextIv?.setOnClickListener {
                playerViewModel.playNext()
            }
            //播放上一首
            playerPreIv?.setOnClickListener {
                playerViewModel.playPre()
            }
            //播放模式切换
            playerModechangeIv.setOnClickListener {
                currentMode = when (currentMode) {
                    PlayMode.SORT -> {
                        ToastUtil.showToast("已切换到单曲循环播放模式")
                        playerModechangeIv.setImageResource(R.drawable.selecter_loop_one_btn)
                        himaPopupWindow.setPlayMode(playmode[PlayMode.SORT]!!)
                        playmode[PlayMode.SORT]!!
                    }
                    PlayMode.RANDOM -> {
                        ToastUtil.showToast("已切换到顺序播放模式")
                        playerModechangeIv.setImageResource(R.drawable.selecter_sort_loop_btn)
                        himaPopupWindow.setPlayMode(playmode[PlayMode.RANDOM]!!)
                        playmode[PlayMode.RANDOM]!!
                    }
                    PlayMode.LOOP -> {
                        ToastUtil.showToast("已切换到随机播放模式")
                        playerModechangeIv.setImageResource(R.drawable.selecter_random_loop_btn)
                        himaPopupWindow.setPlayMode(playmode[PlayMode.LOOP]!!)
                        playmode[PlayMode.LOOP]!!
                    }
                }
                playerViewModel.setPlayMode(currentMode)


            }
            //歌曲列表点击弹出
            playerListIv.setOnClickListener {
                himaPopupWindow.showAtLocation(it, Gravity.BOTTOM, 0, 0)
                enterAnimator.start()
            }
            //popwindow关闭
            himaPopupWindow.setOnDismissListener {
                exitAnimator.start()
            }
            //popwindow点击事件
            himaPopupWindow.setOnItemClickListenter(object : HimaPopupWindow.OnItemClickListenter {
                override fun onClick(position: Int) {
                    playerViewModel.playByIndex(position)
                }

            })
            //进度条触摸事件
            playerDurationSb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(p0: SeekBar?, currProgress: Int, p2: Boolean) {
                    //进度条改变
                    if (currProgress == 99) {
                        playerViewModel.playNext()
                    }

                }

                override fun onStartTrackingTouch(p0: SeekBar?) {
                    //进度条被触摸
                    isTouch = true

                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                    //进度条触摸松手
                    var progress = seekBar!!.progress / 100f
                    com.achun.ximalayamvvm.utils.LogUtil.e(this, "当前进度为--${progress.toFloat()}")
                    playerViewModel.seekTo(progress)
                    isTouch = false
                }

            })
        }
        //
    }

    fun UpdataView(contentView: ActivityPlayerBinding?, track: TracksIndex) {
        contentView?.also {
            track?.run {
                it.playerTitleTv.text = track.run {
                    //保存当前播放列表
                    currentTracks = this.tracks
                    this.tracks[position].trackTitle

                }
                var allduration = tracks[position].duration * 1000
                it.playerAlltimeTv.text = SimpleDateFormat("mm:ss").format(allduration)

            }
        }
    }


}